package com.alageek.personalblog.web;

import com.alageek.personalblog.common.constant.BlogConstant;
import com.alageek.personalblog.entity.query.PostQuery;
import com.alageek.personalblog.entity.vo.LabelVo;
import com.alageek.personalblog.entity.vo.PostVo;
import com.alageek.personalblog.service.LabelService;
import com.alageek.personalblog.service.PostService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * 标签控制器
 * @author AlaGeek
 */
@Slf4j
@Controller
@RequestMapping("/tag")
public class TagController {

    private final LabelService labelService;
    private final PostService postService;

    public TagController(LabelService labelService, PostService postService) {
        this.labelService = labelService;
        this.postService = postService;
    }

    @GetMapping("/list")
    public String list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
            @RequestParam(value = "labelId", defaultValue = "-1") Integer labelId,
            ModelMap modelMap) {
        // 参数校验（待写）
        // 获取所有类型
        List<LabelVo> labelVoList = labelService.countPostGroupByLabelId(-1);
        if (labelVoList == null) {
            labelVoList = new ArrayList<>();
        }
        modelMap.addAttribute(BlogConstant.ATTR_NAME_COUNT, labelVoList.size());
        modelMap.addAttribute(BlogConstant.ATTR_NAME_LABEL_LIST, labelVoList);
        // 获取labelId对应的博客
        if (pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }
        PostQuery postQuery = new PostQuery();
        if (labelId == -1) {
            if (labelVoList.size() > 0 && labelVoList.get(0) != null) {
                labelId = labelVoList.get(0).getId();
            }
        }
        postQuery.setLabelId(labelId);
        List<PostVo> postVoList = postService.findByParamWithLabel(postQuery);
        modelMap.addAttribute(BlogConstant.ATTR_NAME_POST_LIST, postVoList);
        modelMap.addAttribute(BlogConstant.ATTR_NAME_LABEL_ID, labelId);
        return "tag-list";
    }

}
